<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@ taglib uri="http://shiro.apache.org/tags" prefix="shiro" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>合同列表</title>
    <script src="../../js/myutil.js"></script>
</head>
<body>
<!-- 搜索框 -->
<form class="layui-form">
    <blockquote class="layui-elem-quote quoteBox">
        <div class="layui-inline">
            <div class="layui-input-inline" style="width: 400px;">
                <input type="text" class="layui-input " name="name" placeholder="请输入客户名称，支持模糊搜索">
            </div>
            <button type="button" class="layui-btn" data-type="reload" id="searchButton">搜索</button>
        </div>

        <shiro:hasPermission name="crm:order:add">
            <div class="layui-inline">
                <button type="button" class="layui-btn layui-btn-warm" id="add-button">添加</button>
            </div>
        </shiro:hasPermission>

        <shiro:hasPermission name="crm:order:delete">
            <div class="layui-inline">
                <button type="button" class="layui-btn layui-btn-danger layui-btn-normal" id="delete-button">删除</button>
            </div>
        </shiro:hasPermission>
    </blockquote>
</form>

<!-- 要显示的表格 id是必须的 -->
<table class="layui-hide" id="order-table" lay-filter="order-table">
</table>

<script type="text/html" id="table-bar">
    <shiro:hasPermission name="crm:order:view">
        <%--<a class="layui-btn layui-btn-xs" lay-event="detail">合同条目</a>--%>
    </shiro:hasPermission>
    <shiro:hasPermission name="crm:order:update">
        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    </shiro:hasPermission>
    <shiro:hasPermission name="crm:order:delete">
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </shiro:hasPermission>
</script>

<script>
    layui.use(['table', 'element'], function () {
        var $ = layui.jquery;
        var table = layui.table;
        var layer = layui.layer;
        var element = layui.element;

        //加载表格数据
        var tableload = layer.load(2);
        table.render({
            elem: '#order-table'        //html中表格的id
            , even: true				//开启隔行变色
            , url: '/orders/getHistoryOrdersByCustomer'   //数据接口
            , method: 'post'
            , page: true //开启分页
            , cols: [[ //表头
                {type: 'checkbox'}
                , {field: 'id', title: 'ID', align: 'center', width: 100, sort: true,}//fixed: 'left'
                , {
                    field: 'customer', title: '客户名称',
                    templet: function (data) {
                        if (data.customer) {
                            return data.customer.name;
                        }
                        return data.customerId;
                    }
                }, {
                    field: 'date', title: '合同签订日期', width: '10%',
                    templet: function (data) {
                        return Format(data.date, "yyyy-MM-dd");
                    }
                }, {field: 'price', title: '合同总额（元）'}
                , {field: 'address', title: '客户归属地区'}
                , {field: 'orderNum', title: '合同编号', width: '20%'}
                , {
                    field: 'status', title: '合同状态',
                    templet: function (data) {
                        if (data.status == '1') {
                            return "<span style='color:blue;'>" + "已完成" + "</span>";
                        } else {
                            return "<span style='color:red;'>" + "进行中" + "</span>";
                        }
                    }
                }
                , {fixed: 'right', title: "操作", align: 'center', width: 200, toolbar: '#table-bar'}
            ]],
            done: function () {
                layer.close(tableload);
            }
        });

        //监听数据操作按钮
        table.on('tool(order-table)', function (obj) {
            var data = obj.data;
            if (obj.event === 'detail') {
                getOrderItem(data);
            } else if (obj.event === 'del') {
                layer.confirm('真的删除该合同项吗?', function (index) {
                    layer.close(index);
                    deleteData(data.id);
                });
            } else if (obj.event === 'edit') {
                //显示表单
                showForm('更新合同', data.id);
            }
        });

        //删除操作
        function deleteData(id) {
            var index = 0;
            $.ajax({
                type: "POST",
                url: '/orders/delete',
                data: {"id": id},
                dataType: "json",
                //请求前执行
                beforeSend: function () {
                    load = layer.load(2);//显示加载动画
                },
                complete: function () {//请求完成执行，无论请求是否成功
                    layer.close(load);//关闭加载动画
                },
                success: function (data) {
                    layer.msg(data.msg);
                    if (data.success) {//成功
                        //执行重载
                        table.reload('order-table', {
                            page: {
                                curr: 1 //重新从第 1 页开始
                            }
                        });
                    }
                },
                error: function () {
                    layer.msg("服务器开小差了，请稍后再试...");
                }

            });
        }

        //批量删除
        $('#delete-button').click(function () {

            var checkStatus = table.checkStatus('order-table')
                , data = checkStatus.data;
            if (data.length <= 0) {
                layer.msg('请至少选择一行数据');
                return;
            }

            var showStr = '你确定删除以下客户合同吗？<br>';
            layui.each(data, function (index, item) {
                if (item.customer)
                    showStr += ("客户：" + item.customer.name + " 合同编号：" + item.orderNum) + '<br>';
                else
                    showStr += ("合同编号：" + item.orderNum) + '<br>';
            });

            layer.confirm(showStr, {icon: 7, title: '确认删除'}, function (index) {
                layer.close(index);

                var ids = [];
                layui.each(data, function (index, item) {
                    ids.push(item.id);
                });
                console.log(data, ids)
                $.ajax({
                    type: "POST",
                    url: '${pageContext.request.contextPath}/orders/batchDelete',
                    data: {"ids": ids},
                    traditional: true,
                    dataType: "json",
                    success: function (data) {
                        if (data.success) {
                            //执行重载
                            table.reload('order-table', {});
                        }
                        var str = '<div style="padding: 20px;text-align:left;" >删除完成<br>';
                        str += '成功条目：' + data.success.length + ' <br>';
                        str += '失败条目：' + data.fail.length + ' <br>';
                        str += '合计条目：' + ids.length + ' <br></div>';
                        var index = layer.open({
                            type: 1,
                            title: '操作完成',
                            btn: '确定',
                            content: str,
                            end: function () {
                                layer.close(index);
                                table.reload('order-table');
                            }
                        });
                    },
                    error: function () {
                        layer.msg("服务器开小差了，请稍后再试...");
                    }
                });
            })
        });


        //搜索功能
        $('#searchButton').on('click', function () {
            //执行重载
            table.reload('order-table', {
                page: {
                    curr: 1 //重新从第 1 页开始
                }
                , where: {
                    name: $('input[name=name]').val()
                }
            });

        });


        //查看合同条目明细子项
        function getOrderItem(data) {
            var window = layer.open({
                type: 2,
                title: '合同条目明细',
                area: ['80%', '80%'],
                closeBtn: 1,
                //area: '516px',
                //skin: 'layui-bg-black', //没有背景色
                shade: 0.5,
                shadeClose: false,
                content: 'views/order/item.jsp?orderId=' + data.id,
            });
        }

        //点击添加按钮
        $('#add-button').click(function () {
            showForm('添加合同订单', -1);
        });

        function showForm(title, id) {
            layer.open({
                type: 2,
                title: title,
                closeBtn: 1,
                area: ['35%', '65%'],
                // skin: 'layui-bg-black', //没有背景色
                shadeClose: false,
                content: 'views/order/editorder.jsp?id=' + id,
                end: function () {
                    //执行重载
                    table.reload('order-table', {
                        page: {
                            curr: 1 //重新从第 1 页开始
                        }
                    });
                }
            });
        }
    });

</script>

</body>
</html>